package com.example.tests;

import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.example.pages.LoginPage;
import com.example.pages.InternalPage;

import ru.esteru.selenium.factory.WebDriverFactory;

public class LoginLogout {
	private static WebDriver driver;
	private static WebDriverWait wait;
	private static String baseUrl;

	@BeforeClass
	public static void setUp() throws Exception {
		driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		wait = new WebDriverWait(driver, 10);
		baseUrl = "http://localhost/";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	public LoginPage loginPage;
	public InternalPage somePage;

	@Test
	public void loginAndLogout() {
		goToMainPage();
		loginAs("admin", "admin");
		logOut();
		assertTrue("No login form!", loginPage.isOnThisPage());
	}

	private void loginAs(String userName, String password) {

		loginPage.userNameField.clear();
		loginPage.userNameField.sendKeys(userName);
		loginPage.passwordField.clear();
		loginPage.passwordField.sendKeys(password);
		loginPage.loginButton.click();
	}

	private void goToMainPage() {
		driver.get(baseUrl + "/php4dvd/");
		loginPage = PageFactory.initElements(driver, LoginPage.class);
		somePage = PageFactory.initElements(driver, InternalPage.class);
	}

	private void logOut() {
		somePage.menuLogoutLink.click();
		wait.until(alertIsPresent()).accept();
	}

}
